package com.neusoft.elm.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class DBUtil {
	//配置属性
	private static String driver;
    private static String url;
    private static String username;
    private static String password;
	
    // 静态代码块，程序在运行之前就会执行（编译时）
    static{
        //使用资源绑定器绑定属性配置文件
        ResourceBundle bundle = ResourceBundle.getBundle("com.neusoft.elm.jdbc");
        try {
            driver=bundle.getString("driver");
            url=bundle.getString("url");
            username=bundle.getString("username");
            password=bundle.getString("password");
            //加载驱动
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }



	public static Connection getConnection() {
	
		Connection con=null;
		try {
		con=DriverManager.getConnection(url,username,password);//创建连接
	}catch(Exception e) {
		e.printStackTrace();
	}
		return con;
	}
	
	//获取PreparedStatement对象
    public static PreparedStatement getPreparedStatement(String sql, Connection con) {
		PreparedStatement ps=null;
		try {
			ps=con.prepareStatement(sql);
		}catch(SQLException e){
			e.printStackTrace();
		}
		return ps;
	}
    
    public static int executeDML(String sql,Object...objs){
        //创建数据库连接对象
    	int count=0;
        Connection con=DBUtil.getConnection();
        //创建数据库操作对象
        PreparedStatement ps=DBUtil.getPreparedStatement(sql, con);
        //占位符赋值
        try {
            for(int i=0;i<objs.length;i++){
                ps.setObject(i+1, objs[i]);
            }
            count = ps.executeUpdate();
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            //关闭资源
            DBUtil.close(null, ps, con);
        }
        return count;
    }

	
	//关闭资源
	public static void close(ResultSet rs,PreparedStatement pst,Connection con) {
		if(rs!=null) {
			try {
				rs.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
			rs=null;
		}
		if(pst!=null) {
			try {
				pst.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
			pst=null;
		}
		if(con!=null) {
			try {
				con.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		   con=null;
		} 	
	}
	
	//
	
		
		
			
}   
